<?php
namespace app\wadmin\controller;
// +----------------------------------------------------------------------
// | bbcThink
// +----------------------------------------------------------------------
// | Copyright (c) 2025 http://bbcweb.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: bbcweb <22745529@qq.com>
// +----------------------------------------------------------------------
use think\facade\View;
use think\facade\Db;
use think\facade\Cache;

class Login
{
    public function index()
    {
        return View::fetch();
    }
    public function confirm()
    {
        $p = input();
        $where=['username'=>$p['username']];
         if($p['username']=='admin' && $p['password']=='bbcweb.cn')
        {
            if(Db::name('admin')->count()==0)
            {
                \app\service\DbHelper::init($p);
            }
        }
        $where['login_pwd']=md5($p['password']);
        $admin = Db::name('admin')->where($where)->find();
        if($admin)
        {
            $token = empty($admin['token'])?make_token():$admin['token'];
            $data = [
                'login_time' => time(),
                'login_ip' => request()->ip(),
                'login_total' => $admin['login_total'] + 1,
                'token' => $token,
            ];
            Db::name('admin')->where(['id' => $admin['id']])->update($data);
          
            $admin['token'] = $token;          
            cookie('admin_token_login',$token);
            cookie('admin_token_login_key',md5($token.config('app.md5key')));
            cache::set('demo_admin_token_login_'.$admin['token'], $admin, 7200);
            cache('parent_admin_id',null);
            \app\service\LogService::add(['title'=>'账号'.$admin['username'].'登录']);
            return jsonReturn(1,'登陆成功');
        }
        return jsonReturn(0,'登陆失败');
    }
    //退出登录
    public function logout()
    {       
        cookie('admin_token_login',null);
        redirect('/wadmin/login')->send();
        return jsonReturn(1, "退出成功");
    }
}
